package com.masu.knows.portal.controller;


import com.masu.knows.portal.exception.ServiceException;
import com.masu.knows.portal.model.Comment;
import com.masu.knows.portal.service.ICommentService;
import com.masu.knows.portal.vo.CommentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 沈传尚
 * @since 2021-12-07
 */
@RestController
@RequestMapping("/v1/comments")
@Slf4j
public class CommentController {
    @Resource
    private ICommentService commentService;

    /**
     * 发布评论
     */
    @PostMapping()
    public Comment postComment(
            @Validated CommentVo commentVo, BindingResult result,
            @AuthenticationPrincipal UserDetails user){
        log.debug("接收到表单信息:{}",commentVo);
        if (result.hasErrors()){
            String msg = Objects.requireNonNull(result.getFieldError()).getDefaultMessage();
            throw new ServiceException(msg);
        }
        return  commentService.saveComment(commentVo, user.getUsername());

    }


    /**
     * 删除评论
     */
    @PostMapping(value = "/remove/{id}")
    public String removeComment(@PathVariable("id") Integer id, @AuthenticationPrincipal UserDetails user){
        try {
            boolean isDelete = commentService.removeComment(id, user.getUsername());
            if (isDelete){
                return "删除成功";
            }else {
                return "删除失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }


    /**
     * 修改评论
     */
    @PostMapping(value = "/update/{id}")
    public Comment updateComment(@PathVariable("id") Integer id, @Validated CommentVo commentVo,
                                BindingResult result, @AuthenticationPrincipal UserDetails user){
        log.debug("修改的评论为:{}",commentVo);
        if (result.hasErrors()){
            String msg = Objects.requireNonNull(result.getFieldError()).getDefaultMessage();
            throw new ServiceException(msg);
        }
        return  commentService.updateComment(id,commentVo, user.getUsername());
    }






}
